package com.cyan.app.workflow.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppContext;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.Wap.WebViewActivity;
import com.cyan.app.workflow.base.activity.BaseFragmentActivity;
import com.cyan.app.workflow.common.BadgeView;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.common.LoginProxy;
import com.cyan.app.workflow.fragment.MessageFragment;
import com.cyan.app.workflow.fragment.OperationFragment;
import com.cyan.app.workflow.fragment.SigFragment;
import com.cyan.app.workflow.fragment.SaomaFragment;
import com.cyan.app.workflow.fragment.UserCenterFragment;
import com.cyan.app.workflow.fragment.UserLoginFragment;
import com.cyan.app.workflow.service.MainService;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.Upgrader;

/**
 * Created by GivenTang on 2015/10/30.
 */
public class MainActivity extends BaseFragmentActivity {
    private FragmentTransaction ft;
    private long mExitTime = 0;
    private RadioGroup rg;

    private OperationFragment operationFragment;
    private SigFragment sigFragment;
    private MessageFragment messageFragment;
    private UserCenterFragment userCenterFragment;
    private UserLoginFragment userLoginFragment;
    private SaomaFragment saomaFragment;
    // 下载apk的name
    private String downLoadName = "";
    private static String packgeName = null;
    private AutoLoginReceiver mAutoLoginReceiver;
    private String request = "";
    private LoginProxy.LoginCallback loginCallback = new LoginProxy.LoginCallback() {
        @Override
        public void onLoginStart(String loginType, int tag) {


        }

        @Override
        public void onLoginFinished(String loginType, int resultCode, String msg, int tag) {
            if (resultCode == LoginProxy.RESULT_SUCCESS) {
                showUserFragment();
            } else {
                AppUtils.showTip(MainActivity.this, msg);
            }
        }

        @Override
        public void onLogout() {
            showUserFragment();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Upgrader(this).doUpdate();

        setContentView(R.layout.activity_main);//xml显示界面 by Gao

        MainService.start(this);

        rg = (RadioGroup) findViewById(R.id.icon_rg);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                ft = getSupportFragmentManager().beginTransaction();
                if (getSupportFragmentManager().getFragments() != null) {
                    Fragment fragment = null;
                    for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
                        fragment = getSupportFragmentManager().getFragments().get(i);
                        if (fragment != null && !fragment.isHidden()) {
                            ft.hide(fragment);
                            fragment.onPause();
                        }
                    }
                }
                switch (checkedId) {
                    case R.id.icon_rg_operation://首页
                        if (operationFragment == null) {
                            operationFragment = new OperationFragment();
                            ft.add(R.id.content_frame, operationFragment, OperationFragment.TAG);
                        } else {
                            ft.show(operationFragment);
                            operationFragment.onResume();
                        }
                        break;
                    case R.id.icon_rg_report://签核
                        if (sigFragment == null) {
                            sigFragment = new SigFragment();
                            ft.add(R.id.content_frame, sigFragment, SigFragment.TAG);
                        } else {
                            ft.show(sigFragment);
                            sigFragment.onResume();
                        }
                        break;
                    case R.id.icon_rg_message://信息
                        if (messageFragment == null) {
                            messageFragment = new MessageFragment();
                            ft.add(R.id.content_frame, messageFragment, MessageFragment.TAG);
                        } else {
                            ft.show(messageFragment);
                            messageFragment.onResume();
                        }
                        break;
                    case R.id.icon_rg_user://我的
                        if (AppData.getInstance().isUserLogin()) {
                            if (userCenterFragment == null) {
                                userCenterFragment = new UserCenterFragment();
                                ft.add(R.id.content_frame, userCenterFragment, UserCenterFragment.TAG);
                            } else {
                                ft.show(userCenterFragment);
                                userCenterFragment.onResume();
                            }
                        } else {
                            if (userLoginFragment == null) {
                                userLoginFragment = new UserLoginFragment();
                                ft.add(R.id.content_frame, userLoginFragment, UserLoginFragment.TAG);
                            } else {
                                ft.show(userLoginFragment);
                                userLoginFragment.onResume();
                            }
                        }
                        break;
                    case R.id.icon_saoma://扫码
                        if(request.isEmpty()) {
                             startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), 0x0002);
                           // startActivityForResult(new Intent(MainActivity.this, WebViewActivity.class), 0x0002);
                        }
                        break;
                }
                ft.commitAllowingStateLoss();
            }
        });

        rg.check(R.id.icon_rg_operation);

        ///更新全局变量
        SharedPreferences mSharedPreferences = getSharedPreferences("cyan_config", MODE_PRIVATE);
        String serverIP = mSharedPreferences.getString("ServerIP","192.168.0.251");
        String facno = mSharedPreferences.getString("facno","A");
        String facid = mSharedPreferences.getString("facid","E03BD96D-6BF3-1014-6380-001FE1C4AA87");
        HttpConfig.HTTP_MAIN_BASE_URL = "http://" + serverIP;
        HttpConfig.HTTP_MAIN_SERVER_URL =  HttpConfig.HTTP_MAIN_BASE_URL +"/Services/MainHandler.ashx";
        HttpConfig.HTTP_MAIN_API_URL =  HttpConfig.HTTP_MAIN_BASE_URL +"/api/MainHandler";
        HttpConfig.Main_FacNo = facno;
        HttpConfig.Main_FactoryID = facid;

        registerAutoLoginReceiver();

        LoginProxy.getInstance(this).registerCallback(loginCallback);



        Button btmsg = (Button) findViewById(R.id.icon_message);

        BadgeView badge1 = new BadgeView(this, btmsg);// 创建一个BadgeView对象，view为你需要显示提醒的控件
        badge1.setText("12"); // 需要显示的提醒类容
        badge1.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);// 显示的位置.右上角,BadgeView.POSITION_BOTTOM_LEFT,下左，还有其他几个属性
        badge1.setTextColor(Color.WHITE); // 文本颜色
        badge1.setBadgeBackgroundColor(Color.RED); // 提醒信息的背景颜色，自己设置
        badge1.setTextSize(12); // 文本大小
        //badge1.setBadgeMargin(3, 3); // 水平和竖直方向的间距
        //badge1.setBadgeMargin(5); //各边间隔
        // badge1.toggle(); //显示效果，如果已经显示，则影藏，如果影藏，则显示
        badge1.show();// 只有显示
        // badge1.hide();//影藏显示

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterAutoLoginReceiver();
        LoginProxy.getInstance(this).unRegisterCallback(loginCallback);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if (data != null) {
                result = data.getStringExtra("result");
            }
            String re = String.valueOf(result);
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, WebViewActivity.class);
            intent.putExtra("sm_content", re);
            startActivityForResult(intent, 0x0004);
        }else{
            request = "0x0004";
            rg.check(R.id.icon_rg_operation);
            request ="";
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, R.string.again_to_exit, Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 自动登录
     */
    private void registerAutoLoginReceiver() {
        mAutoLoginReceiver = new AutoLoginReceiver();
        IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(mAutoLoginReceiver, mFilter);
    }

    private void unregisterAutoLoginReceiver() {
        this.unregisterReceiver(mAutoLoginReceiver);
    }

    private class AutoLoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (AppUtils.checkNet(MainActivity.this) && !AppData.getInstance().isUserLogin()) {
                    LoginProxy.getInstance(AppContext.getInstance()).login();
                }
            }
        }
    }

    /**
     * 显示我的栏目
     */
    private void showUserFragment() {
        if(rg.getCheckedRadioButtonId() == R.id.icon_rg_user) {
            ft = getSupportFragmentManager().beginTransaction();
            if (AppData.getInstance().isUserLogin()) {
                if(userLoginFragment != null) {
                    ft.hide(userLoginFragment);
                    userLoginFragment.onPause();
                }
                if (userCenterFragment == null) {
                    userCenterFragment = new UserCenterFragment();
                    ft.add(R.id.content_frame, userCenterFragment, UserCenterFragment.TAG);
                } else {
                    ft.show(userCenterFragment);
                    userCenterFragment.onResume();
                }
                /*if (operationFragment == null) {
                    operationFragment = new OperationFragment();
                    ft.add(R.id.content_frame, operationFragment, OperationFragment.TAG);
                } else {
                    ft.show(operationFragment);
                    operationFragment.onResume();
                }
                rg.check(R.id.icon_rg_operation);*/
            } else {
                if(userCenterFragment != null) {
                    ft.hide(userCenterFragment);
                    userCenterFragment.onPause();
                }
                if (userLoginFragment == null) {
                    userLoginFragment = new UserLoginFragment();
                    ft.add(R.id.content_frame, userLoginFragment, UserLoginFragment.TAG);
                } else {
                    ft.show(userLoginFragment);
                    userLoginFragment.onResume();
                }
            }
            ft.commitAllowingStateLoss();
        }
    }
}
